package com.jf.yytgd.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Objects;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA
 * Description: 文件工具类
 * User:22954
 * Date:2025-01-14
 * Time:16:33
 */
@Slf4j
public class FileUtil {
    private static String DEFAULT_FILE_PATH = null;
    private static final String DEFAULT_STATIC_FOLDER = "WEB-INF/static/";

    public static void init(ApplicationContext context) {
        Environment env = context.getEnvironment();
        DEFAULT_FILE_PATH = env.getProperty("static.file-path");
        if (!StringUtils.hasText(DEFAULT_FILE_PATH)) {
            DEFAULT_FILE_PATH = Objects.requireNonNull(FileUtil.class.getClassLoader().getResource("")).getPath();
            DEFAULT_FILE_PATH += DEFAULT_STATIC_FOLDER;
        }
    }

    public static String saveFile(MultipartFile file, String folderName){
        String folderPath = DEFAULT_FILE_PATH + folderName;
        File folder = new File(folderPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
        String fullPath = folderPath + fileName;
        //System.out.println(fullPath);
        try {
            file.transferTo(new File(fullPath));
        } catch (IOException e) {
            log.warn("File save error", e);
            return null;
        }
        return fullPath;
    }

    public static String  saveFile(MultipartFile file){
        return saveFile(file, getYMD());
    }

    private static String getYMD() {
        LocalDate localDate = LocalDate.now();
        return localDate.getYear() + "/" + localDate.getMonthValue() + "/" + localDate.getDayOfMonth() + "/";
    }
}
